import { connection } from '../app/database/mysql';
import { adminModel } from './admin.model';

/**
 * 获取内容
 */
export const getAdmin = async () => {
  // 准备查询
  const statement = `
    SELECT * FROM admin
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement);

  // 提供数据
  return data;
}

/**
 * 获取管理员信息
 */
export const getAdminCon = async (id: adminModel) => {
  // 准备查询
  const statement = `
    SELECT
      level
    FROM admin
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, id);

  // 提供数据
  return data;
}

/**
 * 创建用户
 */
export const createAdmin = async (admin: adminModel) => {
  // 准备查询
  const statement = `
    INSERT INTO admin
    SET ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, admin);

  // 提供数据
  return data;
}

/**
 * 按用户名查找用户
 */
interface GetAdminOptions {
  password?: boolean;
}

/**
 * 状态
 */
export const adminStatusChange = async (postId: number, post: any) => {
  // 准备数据
  const statement = `
    UPDATE admin
      SET ?
      WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, [post, postId]);

  // 提供数据
  return data;
};

/**
 * 删除内容
 */
export const deleteAdmin = async (postId: number) => {
  // 准备查询
  const statement = `
    DELETE FROM admin
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, postId);

  // 提供数据
  return data;
}

export const getAdminByName = async (name: string, options: GetAdminOptions = {}) => {
  // 准备选项
  const { password } = options;

  // 准备查询
  const statement = `
    SELECT 
      id,
      name
      ${password ? ', password' : ''}
    FROM admin
    WHERE name = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, name);

  // 提供数据
  return data[0];
}
